from utilities.utils import flat, get_flat_value


class RequestFilter(object):
    allow_request_args = ()

    def filter_request(self):
        request = getattr(self, 'request')
        model = getattr(self, 'serializer_class').Meta.model()

        # Set data
        for item in self.allow_request_args:
            temp_v = request.data
            temp_model = model

            for k in item.split('.'):
                if not isinstance(temp_v[k], dict):
                    setattr(temp_model, k, temp_v[k])
                    break
                else:
                    temp_v = temp_v[k]
                    temp_model = getattr(temp_model, k)

        # Fill data
        for k, v in model.to_dict().items():
            request.data[k] = v


class ResponseFilter(object):
    exclude_response_key = ()

    def filter_response(self, response):
        if response.status_code != 200:
            return response
        for item in self.exclude_response_key:
            temp_v = response.data
            k_list = item.split('.')
            length = len(k_list)

            for i, k in enumerate(k_list):
                if i + 1 == length:
                    temp_v.pop(k, None)
                    break
                if isinstance(temp_v[k], dict):
                    temp_v = temp_v[k]

        return response
